package com.unswift.cloud.pojo.dao.sql;

import java.util.List;

import com.unswift.annotation.api.ApiEntity;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.utils.ObjectUtils;

@SuppressWarnings("serial")
@ApiEntity(value="查询的条件", author = "unswift", date = "2024-04-14", version = "1.0.0")
public class SqlWhere implements SqlKeyword{

	@ApiField("逻辑条件{and,or}")
	private String logic;
	@ApiField("逻辑开始")
	private Boolean start;
	@ApiField("字段名称")
	private String field;
	@ApiField("比较运算{=,>,<,!=,<>,BETWEEN,IN,LIKE,NOT LIKE,EXISTS,NOT EXISTS,IN}")
	private String compare;
	@ApiField("值集合")
	private List<Object> valueList;
	@ApiField("逻辑开始")
	private Boolean end;
	
	public SqlWhere(String logic, String field, String compare, Object...valueArray) {
		super();
		this.logic = logic;
		this.field = field;
		this.compare = compare;
		this.valueList = ObjectUtils.asList(valueArray);
		this.start=false;
		this.end=false;
	}
	public SqlWhere(String logic, boolean start, boolean end, String field, String compare, Object...valueArray) {
		super();
		this.logic = logic;
		this.field = field;
		this.compare = compare;
		this.valueList = ObjectUtils.asList(valueArray);
		this.start=start;
		this.end=end;
	}
	public String getLogic() {
		return logic;
	}
	public void setLogic(String logic) {
		this.logic = logic;
	}
	public String getField() {
		return field;
	}
	public void setField(String field) {
		this.field = field;
	}
	public String getCompare() {
		return compare;
	}
	public void setCompare(String compare) {
		this.compare = compare;
	}
	public List<Object> getValueList() {
		return valueList;
	}
	public void setValueList(List<Object> valueList) {
		this.valueList = valueList;
	}
	public Boolean getStart() {
		return start;
	}
	public void setStart(Boolean start) {
		this.start = start;
	}
	public Boolean getEnd() {
		return end;
	}
	public void setEnd(Boolean end) {
		this.end = end;
	}
	
	@Override
	@ApiMethod(value="将当前where对象转换为sql语句", returns=@ApiField("sql语句"))
	public String toSql() {
		StringBuilder sql=new StringBuilder();
		sql.append(ObjectUtils.init(logic, LOGIC_AND)).append(SPACE);
		if(compare.contains(COMPARE_EXISTS)){
			sql.append(compare).append(LEFT_BRACKET).append(valueList.get(0)).append(RIGHT_BRACKET);
		}else {
			sql.append(field).append(SPACE).append(compare);
			if(compare.equals(COMPARE_IN)){
				sql.append(LEFT_BRACKET);
				for (Object value : valueList) {
					sql.append(value).append(COMMA);
				}
				if(ObjectUtils.isNotEmpty(valueList)) {
					sql.deleteCharAt(sql.length()-1);
				}
				sql.append(RIGHT_BRACKET);
			}else if(compare.equals(COMPARE_BETWEEN)){
				sql.append(SPACE).append(valueList.get(0)).append(LOGIC_AND).append(valueList.get(1));
			}else{
				sql.append(SPACE).append(valueList.get(0));
			}
		}
		return sql.toString();
	}
}
